package com.ikun.usercenter.service.impl;
import java.util.Date;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ikun.usercenter.common.ErrorCode;
import com.ikun.usercenter.exception.BusinessException;
import com.ikun.usercenter.service.UserService;
import com.ikun.usercenter.domain.User;
import com.ikun.usercenter.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import static com.ikun.usercenter.constant.UserConstant.USER_LOGIN_STATE;
import javax.servlet.http.HttpServletRequest;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 用户服务实现类
* @author 顾琴
*/
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService {

    //盐值混淆密码
    private  static final String SALT = "GuQin";


    @Override
    public Long userRegister(String userAccount, String userPassword, String checkPassword,String genshinUID) {
        //1.校验
        if(StringUtils.isAnyBlank(userAccount,userPassword,checkPassword,genshinUID)){
        throw new BusinessException(ErrorCode.PARAMS_ERROR,"参数为空");
        }
        if(userAccount.length() < 4){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"用户账号过短");
        }
        if(userPassword.length() < 8 || checkPassword.length() < 8){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"用户密码过短");
        }

        if(genshinUID.length()!=9)
        {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"原神UID应为9位");
        }



        //账户不能包含特殊字符
        final String SYMBOL_PATTERN = "[!@#$%^&*()\\-=_+\\[\\]{};':\"\\\\|,.<>/?]";
        Pattern pattern = Pattern.compile(SYMBOL_PATTERN);
        Matcher matcher = pattern.matcher(userAccount);

        if(matcher.find()) {
           throw new BusinessException(ErrorCode.WRONG_ACCOUNT,"账号不能包含特殊字符");
        }


        //密码要与校验密码相同
        if(!userPassword.equals(checkPassword)){
            throw new BusinessException(ErrorCode.PWD_MUST_SAME,"两次密码输入不一致");
        }

        //账户不能重复
        LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<User>();
        lqw.eq(User::getUserAccount,userAccount);
        long count = this.count(lqw);
        if(count > 0){
            throw new BusinessException(ErrorCode.IS_EXISTS,"账户不能重复");
        }

        //GenshinUID查询
        lqw = new LambdaQueryWrapper<User>();
        lqw.eq(User::getGenshinUID,genshinUID);
        count = this.count(lqw);
        if(count > 0){
           throw new BusinessException(ErrorCode.IS_EXISTS,"原神UID不能重复");
        }
        //对密码进行加密
        //在此处可以进行加盐操作(即将加密内容进行进一步的混淆，鱼皮语录：搅屎棍)

        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());


        //插入数据
        User user = new User();
        user.setUserAccount(userAccount);
        user.setUserPassword(encryptPassword);
        user.setGenshinUID(genshinUID);
        boolean saveResult = this.save(user);

        if(!saveResult)
            return -1L;


        return user.getId();




    }

    @Override
    public User userLogin(String userAccount, String userPassword, HttpServletRequest request) {
        //1.校验
        if(StringUtils.isAnyBlank(userAccount,userPassword)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"账号或密码不能为空");
        }
        if(userAccount.length() < 4){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"账号不得低于四位");
        }
        if(userPassword.length() < 8){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"密码不得低于8位");
        }




        //账户不能包含特殊字符
        String SYMBOL_PATTERN = "[!@#$%^&*()\\-=_+\\[\\]{};':\"\\\\|,.<>/?]";
        Pattern pattern = Pattern.compile(SYMBOL_PATTERN);
        Matcher matcher = pattern.matcher(userAccount);

        if(matcher.find()) {
            log.info("userLogin failed, userAccount cannot match userPassword");
            throw new BusinessException(ErrorCode.WRONG_ACCOUNT,"账号不能包含特殊字符");
        }




        //对密码进行加密
        //在此处可以进行加盐操作(即将加密内容进行进一步的混淆，鱼皮语录：搅屎棍)
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());

        //查询用户是否存在
        LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<User>();
        lqw.eq(User::getUserAccount,userAccount).eq(User::getUserPassword,encryptPassword);
        User user = this.getOne(lqw);

        //用户不存在
        if(user == null){
            log.info("userLogin failed, userAccount cannot match userPassword");
            throw new BusinessException(ErrorCode.WRONG_PWD,"账户密码不匹配");
        }



        //用户脱敏

        User safeUser = getSafeUser(user);

        //记录用户的登录态
        request.getSession().setAttribute(USER_LOGIN_STATE,safeUser);




        return safeUser;
    }

    /**
     * 用户脱敏
     * @param originUser
     * @return
     */

    @Override
    public User getSafeUser(User originUser) {
        if(originUser == null)
            return null;
        User safeUser = new User();
        safeUser.setId(originUser.getId());
        safeUser.setUsername(originUser.getUsername());
        safeUser.setUserAccount(originUser.getUserAccount());
        safeUser.setAvatarUrl(originUser.getAvatarUrl());
        safeUser.setGender(originUser.getGender());
        safeUser.setPhone(originUser.getPhone());
        safeUser.setEmail(originUser.getEmail());
        safeUser.setUserRole(originUser.getUserRole());
        safeUser.setUserStatus(originUser.getUserStatus());
        safeUser.setCreateTime(originUser.getCreateTime());
        safeUser.setGenshinUID(originUser.getGenshinUID());
        return safeUser;
    }

    /**
     * 用户注销
     * @param request
     */

    @Override
    public int userLogout(HttpServletRequest request) {
        //移除登录态
        request.getSession().removeAttribute(USER_LOGIN_STATE);
        return 1;
    }

}




